package com.xueyi.core.base;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xueyi.core.constants.SystemCode;
import com.xueyi.core.utils.AesUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 描述 Ase加密耨的Response
 *
 * @author 俞烨
 * @date 2022-08-02 11
 */
@Data
public class AesResponse<T> extends BaseResponse<T> {

    private Boolean ase = Boolean.TRUE;
    private String aesContent;
    private String aesKey;

    /**
     * aes加密
     *
     * @param baseResponse
     * @param <T>
     * @return
     */
    public static <T> AesResponse<T> aes(Object baseResponse) {

        AesResponse<T> response = new AesResponse<T>();

        // 分割Key的信息
        String aseKey = generateAesKey();
        response.setAesContent(AesUtil.enCode(JSON.toJSONString(baseResponse, SerializerFeature.WriteMapNullValue), aseKey));
        response.setAesKey(aseKey);
        response.setCode(SystemCode.SUCCESS);
        return response;
    }


    public void setAesKey(String aesKey) {

        // 对Key进行乱序处理
        List<Integer> charIndexArr = new ArrayList<>(AesUtil.RANDOM);
        Collections.shuffle(charIndexArr);

        // 组建新的AesKey
        StringBuilder aesKeyBuf = new StringBuilder();
        for (Integer aesKeyIndex : charIndexArr) {
            aesKeyBuf.append(aesKey.charAt(aesKeyIndex));
        }
        this.aesKey = aesKeyBuf.toString();
    }

    private static String generateAesKey() {
        String backToken = IdUtil.fastSimpleUUID();
        String aseKey = backToken.substring(backToken.length() - 16);

        // 对ASCII进行排序加密
        char[] aesKeyArr = aseKey.toCharArray();
        Arrays.sort(aesKeyArr);
        // 排序好的Key需要进行换位
        char oneKey = aesKeyArr[3];
        char twoKey = aesKeyArr[7];
        char threeKey = aesKeyArr[15];
        aesKeyArr[3] = threeKey;
        aesKeyArr[7] = oneKey;
        aesKeyArr[15] = twoKey;
        return new String(aesKeyArr);

    }
}
